from flask import current_app, abort, g, jsonify, render_template, request

from . import news_blue
from ... import db

from ...common import user_login_data
from ...models import News, Comment, Category, User
from ...response_code import RET, error_map


# 1. 新闻详情页的展示
@news_blue.route('/<int:news_id>')
@user_login_data
def news_detail(news_id):
    try:
        news = News.query.get(news_id)
    except BaseException as e:
        current_app.logger.error(e)
        return abort(404)
    news_list = []
    try:
        news_list = News.query.order_by(News.clicks.desc()).limit(10).all()
    except BaseException as e:
        current_app.logger.error(e)
    news_list = [news.to_dict() for news in news_list]

    news.clicks += 1
    user = g.user
    # 查用户的是否收藏了这条新闻
    is_collect = False
    if user:
        if news in user.collection_news:
            is_collect = True
    # 查询评论
    try:
        comments = news.comments.order_by(Comment.create_time.desc()).all()

    except BaseException as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg=error_map[RET.DBERR])
    comment_list = []
    for comment in comments:
        comment_dict = comment.to_dict()
        is_like = False
        if user:
            if comment in user.like_comments:
                is_like = True
        comment_dict["is_like"] = is_like
        comment_list.append(comment_dict)

    # 作者你是否关注
    is_followed = False
    if user and news.user:
        if news.user in user.followed:
            is_followed = True

    user = user.to_dict() if user else None

    category_list = Category.query.all()

    # 一共要渲染哪些数据：用户,前十点击，当前新闻，是否收藏，用户消息，是否关注该作者，哪些评论，评论是否点赞
    return render_template("news/detail.html", news=news.to_dict(), news_list=news_list, user=user,
                           is_collect=is_collect, comments=comment_list, is_followed=is_followed,
                           category_list = category_list)


# 2.用户新闻的收藏
@news_blue.route("/news_collect", methods=["POST"])
@user_login_data
def news_collect():
    user = g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg=error_map[RET.SESSIONERR])
    news_id = request.json.get("news_id")
    action = request.json.get("action")
    if not all([news_id, action]):
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])
    if action not in ["collect", "cancel_collect"]:
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])

    try:
        news_id = int(news_id)
    except BaseException as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR,errmsg=error_map[RET.PARAMERR])
    try:
        news = News.query.get(news_id)
    except BaseException as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR,errmsg=error_map[RET.PARAMERR])

    if action == "collect":
        user.collection_news.append(news)

    if action == "cancel_collect":
        user.collection_news.remove(news)

    return jsonify(errno=RET.OK, errmsg=error_map[RET.OK])


# 3.用户的关注
@news_blue.route("/followed_user", methods=["POST"])
@user_login_data
def user_follow():
    user = g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR,errmsg=error_map[RET.SESSIONERR])
    user_id = request.json.get("user_id")
    action = request.json.get("action")

    if not all([user_id,action]):
        return jsonify(errno=RET.PARAMERR,errmsg=error_map[RET.PARAMERR])
    if action not in ["follow","unfollow"]:
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])

    try:
        user_id = int(user_id)
    except BaseException as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR,errmsg=error_map[RET.PARAMERR])

    try:
        author = User.query.get(user_id)
    except BaseException as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])

    if action == "follow":
        user.followed.append(author)
    if action == "unfollow":
        user.followed.remove(author)
    return jsonify(errno=RET.OK,errmsg=error_map[RET.OK])


# 4.用户评论/回复->简易版的评论回复
@news_blue.route("/news_comment", methods=["POST"])
@user_login_data
def news_comment():
    user = g.user
    if not user:
        return jsonify(errno=RET.PARAMERR, errmsg = error_map[RET.PARAMERR])

    news_id = request.json.get("news_id")
    comment_content = request.json.get("comment")
    parent_id = request.json.get("parent_id") # 要知道这个是父评论还是子评论
    if not all([news_id, comment_content]):
        return jsonify(errno=RET.PARAMERR,errmsg = error_map[RET.PARAMERR])

    try:
        news_id = int(news_id)
    except BaseException as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg = error_map[RET.PARAMERR])

    try:
        news = News.query.get(news_id)
    except BaseException as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg = error_map[RET.DBERR])
    if not news:
        return jsonify(errno=RET.PARAMERR,errmsg=error_map[RET.PARAMERR])
    comment = Comment()
    comment.news_id = news_id
    comment.user_id = user.id
    comment.content = comment_content
    if parent_id:
        try:
            parent_id = int(parent_id)
            comment.parent_id = parent_id
        except BaseException as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.PARAMERR,errmsg=error_map[RET.PARAMERR])

    try:
        db.session.add(comment)
        db.session.commit()
    except BaseException as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg=error_map[RET.DBERR])
    return jsonify(errno=RET.OK,errmsg=error_map[RET.OK],data=comment.to_dict())


# 5.用户评论点赞
@news_blue.route("/comment_like", methods=["POST"])
@user_login_data
def comment_like():
    user = g.user
    if not user:
        return jsonify(errno=RET.PARAMERR,errmsg=error_map[RET.PARAMERR])
    comment_id = request.json.get("comment_id")
    action = request.json.get("action")
    if not all([comment_id,action]):
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])
    if action not in ["add", "remove"]:
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])
    try:
        comment_id = int(comment_id)
    except BaseException as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR,errmsg=error_map[RET.PARAMERR])
    try:
        comment = Comment.query.get(comment_id)
    except BaseException as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg=error_map[RET.DBERR])

    if action == "add":
        user.like_comments.append(comment)
        comment.like_count += 1
    if action == "remove":
        user.like_comments.remove(comment)
        comment.like_count += 1
    return jsonify(errno=RET.OK, errmsg=error_map[RET.OK])
